﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.UI.WebControls;
using System.Xml;

namespace SystmicFunction.Public.FileService
{
    /// <summary>
    ///     TODO：图像预览
    /// TODO;部分实现，未考虑线程安全
    /// </summary>
    public class FileHelper
    {


        #region 写入



        #endregion

        #region Txt

        /// <summary>
        ///     写入或追加本地TXT文本内容
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="context">内容</param>
        private static void WriteLocalTxt(string file, string context)
        {
            System.IO.File.AppendAllText(file, context);
        }

        #endregion

        #region XML

        /// <summary>
        ///     迭代
        /// </summary>
        /// <param name="file"></param>
        /// <param name="data"></param>
        public static void SaveXml(String file, IList<XmlData> data)
        {
            var xml = new XmlDocument();
            xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", null));
            var root = xml.CreateElement("xml");
            xml.AppendChild(root);
            //xml.Load(file);


            foreach (var xmlData in data)
            {
                var node = xml.CreateElement(xmlData.Name);
                foreach (var att in xmlData.Attributes)
                {
                    node.SetAttribute(att.Key, att.Value);
                }
                if (xmlData.ChildNode != null)
                {
                    foreach (var cnode in xmlData.ChildNode)
                    {
                        XmlElement childNode = xml.CreateElement(cnode.Name);
                        childNode.InnerText = cnode.Value;
                        foreach (var att in cnode.Attributes)
                        {
                            childNode.SetAttribute(att.Key, att.Value);
                        }
                        node.AppendChild(childNode);
                    }
                }
                root.AppendChild(node);
            }

            xml.Save(file);

            //XmlNode root=xml.SelectSingleNode("bookstore");//查找 

            //root.AppendChild(xe1);//添加到节点中 

        }

        public static IList<XmlData> LoadXml(String file)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(file);

            return new List<XmlData>();
        }

        #endregion

        #region IMG



        public static String SaveFileRootPathName = "UpLoad";

        /// <summary>
        ///     保存HTTP上传的图片
        /// </summary>
        /// <param name="imgUpload">上传的数据源</param>
        /// <param name="savefileName">希望命名的文件名，不含后缀</param>
        /// <param name="savePathName">保存文件名</param>
        /// <returns></returns>
        public static String HttpSaveImg(HttpPostedFileBase imgUpload, String savefileName, String savePathName)
        {
            if (imgUpload == null)
                return "";

            String fileName = ChangeFileName(imgUpload, savefileName);

            if (String.IsNullOrEmpty(fileName))
                return "";

            String filePath = HostingEnvironment.MapPath("~") + String.Format("/{0}/{1}", SaveFileRootPathName, savePathName);

            if (!System.IO.File.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }

            filePath = Path.Combine(filePath, Path.GetFileName(fileName));

            imgUpload.SaveAs(filePath);
            fileName = String.Format("/{0}/{1}/{2}", SaveFileRootPathName, savePathName, fileName);


            return fileName;
        }

        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="cxt">当前容器</param>
        /// <param name="pathbase">保存路径</param>
        /// <returns></returns>
        public static String HttpUploadFile(HttpContext cxt, string pathbase)
        {
            //虚拟路径
            pathbase = String.Format("{0}/{1}/", pathbase, DateTime.Now.ToString("yyyy-MM-dd"));
            //保存的本地路径
            String uploadpath = HostingEnvironment.MapPath("~") + pathbase;

            //目录创建
            CreateFolder(uploadpath);
            var uploadFile = Convert(cxt.Request.Files[0]);

            //更名
            String fileName = ChangeFileName(uploadFile, Guid.NewGuid().ToString());

            uploadFile.SaveAs(uploadpath + fileName);

            return pathbase + fileName;

        }

        /// <summary>
        ///     获得其他信息
        /// </summary>
        /// <param name="cxt"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static string GetOtherInfo(HttpContext cxt, string field)
        {
            string info = null;
            if (cxt.Request.Form[field] != null && !String.IsNullOrEmpty(cxt.Request.Form[field]))
            {
                info = field == "fileName" ? cxt.Request.Form[field].Split(',')[1] : cxt.Request.Form[field];
            }
            return info;
        }

        public static HttpPostedFileBase Convert(HttpPostedFile file)
        {
            return new HttpPostedFileWrapper(file);
        }



        /// <summary>
        /// 按照日期自动创建存储文件夹
        /// </summary>
        /// <param name="path">路径</param>
        private static void CreateFolder(String path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        ///     修改文件名不修改后缀，如果没有找到可以处理的文件类型则返回空字符
        /// </summary>
        /// <param name="file"></param>
        /// <param name="saveFileName"></param>
        /// <returns></returns>
        private static String ChangeFileName(HttpPostedFileBase file, String saveFileName)
        {
            return String.Format("{0}{1}", saveFileName, ImgSuffixNames.SingleOrDefault(m => file.FileName.EndsWith(m))).ToLower();
        }


        /// <summary>
        /// 验证文件类型是否支持
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <param name="types"></param>
        /// <returns>true:不符合 false:符合</returns>
        public static bool CheckType(HttpPostedFileBase uploadFile, String[] types)
        {
            return !types.Any(m => uploadFile.FileName.EndsWith(m));
        }

        /// <summary>
        ///     验证尺寸
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <param name="size">文件大小限制,单位mb</param>
        /// <returns>true:不符合 false:符合</returns>
        public static bool CheckSize(HttpPostedFileBase uploadFile, Int32 size)
        {
            return uploadFile.ContentLength >= (size * 1024 * 1024);
        }


        #region Image Suffix Name

        public static readonly String[] ImgSuffixNames = { ".jpg", ".png", ".gif", ".jpeg", ".bmp" };
        public static readonly String ImgJpg = ".jpg";
        public static readonly String ImgPng = ".png";
        public static readonly String ImgGif = ".gif";
        public static readonly String ImgJpeg = ".jpeg";
        public static readonly String ImgBmp = ".bmp";

        #endregion


        #endregion


    }

    /// <summary>
    ///     输出文件类型
    /// </summary>
    public enum OutFileTypes
    {
        Txt = 1,
        Xml = 2,
        Html = 3,
    }


    public class XmlData
    {
        public String Name { get; set; }

        public String Value { get; set; }

        public Dictionary<String, String> Attributes { get; set; }

        public XmlData[] ChildNode { get; set; }
    }
}